import { Image, Text, View } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { sourceUrl } from '@/config';
import utils from '@/utils/index';
import Icon from '@/components/Icon';
import { debounce } from '@/utils/helper';
import { customeColor } from '@/src/config';
import { checkProductIsSoldOut } from '@/dataTransfer/product';
import { checkDistributionWay } from '@/pages/mainPages/standardCartPage/orgView/helper';
import DistributionWayLayout from '@/pages/mainPages/standardCartPage/orgView/DistributionWayLayout';
import cartImg from '@/images/standBar/cart.png';
import questionImg from '@/mainSubPack/images/takeOutGoodsDetail/question.png';
import './index.scss';
import SkuSelect from '../takeOutShop/skuSelect/index';
import ShoppingCarList from '../takeOutShop/shoppingCar/index';

const TakeOutGoodsDetail = ({ dispatch, productDetail = {}, selectedAddress = {} }) => {
  const [curLocation, setCurLocation] = useState(null);
  const [carProList, setCarProList] = useState([]);
  const [delivery, setDelivery] = useState(null);
  const [totalMoney, setTotalMoney] = useState({ totalPayment: 0, totalPrice: 0 });
  const [productCur, setProductCur] = useState({});
  const [isOpenedSku, setIsOpenedSku] = useState(false);
  const [isOpenedCar, setIsOpenedCar] = useState(false);
  const [distributionWayGroup, setDistributionWayGroup] = useState();

  const router = useRouter();
  const { params = {} } = router;

  const getLocation = async () => {
    if (Object.keys(selectedAddress).length > 0) {
      const { latitude, longitude } = selectedAddress;
      setCurLocation({ latitude, longitude });
      return;
    }

    let localLocation = utils.getLocalEffectLocation();
    if (localLocation) {
      const { latitude, longitude } = localLocation;
      setCurLocation({ latitude, longitude });
    } else {
      Taro.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        timeout: 5000,
        success: (res) => {
          const { latitude, longitude } = res;
          const timeStamp = new Date().getTime();
          setCurLocation({ latitude, longitude });
          utils.setLocalStorage('location', { latitude, longitude, timeStamp });
        },
        fail: () => {
          setCurLocation({});
        },
      });
    }
  };

  const getCarProList = () => {
    if (!utils.getToken()) {
      return;
    }
    let { latitude, longitude } = curLocation || {};
    dispatch({
      type: 'takeOut/getProductCarListModel',
      payload: {
        orgId: params.orgId,
        merchantId: params.merchantId,
        type: 4,
        latitude,
        longitude,
      },
    }).then((result) => {
      const { productCarOrgList: data = [] } = result;
      let theProductInCart = { carNum: 0, carList: [] };

      if (data.length > 0 && data[0]?.products?.length > 0) {
        let products = data[0].products;
        for (let i = 0; i < products.length; i++) {
          let optionSelObj = JSON.parse(products[i].optionValue);
          let selOptionList = [];
          for (let key in optionSelObj) {
            selOptionList.push(optionSelObj[key]);
          }
          products[i].optionSelObj = optionSelObj;
          products[i].optionSelStr = selOptionList.join('/');

          if (products[i].productReleaseId == params.releasedId) {
            theProductInCart.carNum += products[i].num;
            theProductInCart.carList.push(products[i]);
          }
        }
        dispatch({
          type: 'takeOut/refreashProductDetailModel',
          payload: theProductInCart,
        });
        const { isInDelivery = 0, fee = 0 } = data[0];
        setDelivery({ isInDelivery, fee });
        setTotalMoney({ totalPayment: data[0].totalPayment, totalPrice: data[0].totalPrice });
        setCarProList(products);
      } else {
        dispatch({
          type: 'takeOut/refreashProductDetailModel',
          payload: { carNum: 0, carList: [] },
        });
        setDelivery(null);
        setCarProList([]);
        isOpenedCar && setIsOpenedCar(false);
      }
    });
  };

  const goToBuy = (productToPayList = []) => {
    if (productToPayList.length == 0) {
      return;
    }

    const cartIds = productToPayList.map((v) => v.id);
    const productReleaseIds = productToPayList.map(({ productReleaseId }) => productReleaseId);

    dispatch({
      type: 'productCar/setCartShopSelectedByTakeOut',
      payload: cartIds,
    });

    dispatch({
      type: 'productCar/setCartShopProductReleaseIds',
      payload: productReleaseIds,
    });

    Taro.navigateTo({
      url:
        '/orderSubPack/confirmOrder/index?merchantId=' +
        params.merchantId +
        '&orgId=' +
        params.orgId +
        '&type=4',
    });
  };

  const handleGoPay = () => {
    if (!utils.getToken()) {
      Taro.navigateTo({
        url: '/pages/other/login/index',
      });
      return;
    }

    const group = checkDistributionWay(carProList);

    if (group === true) {
      goToBuy(carProList);
      return;
    }

    setDistributionWayGroup(group);
  };

  const getProductDetail = () => {
    dispatch({
      type: 'takeOut/getProductDetailModel',
      payload: {
        releasedId: params.releasedId,
      },
    });
  };

  useEffect(() => {
    getLocation();
    getProductDetail();
  }, []);

  useEffect(() => {
    Object.keys(productCur).length > 0 && setProductCur(productDetail);
  }, [productDetail]);

  useEffect(() => {
    curLocation && getCarProList();
  }, [curLocation]);

  const handleSku = (product) => {
    product.orgId = params.orgId;
    setProductCur(product);
    !isOpenedSku && setIsOpenedSku(true);
  };

  const handleCar = () => {
    if (!utils.getToken()) {
      Taro.navigateTo({
        url: '/pages/other/login/index',
      });
      return;
    }
    carProList.length > 0 && !isOpenedCar && setIsOpenedCar(true);
  };

  const handleClose = () => {
    isOpenedCar && setIsOpenedCar(false);
    if (isOpenedSku) {
      setIsOpenedSku(false);
      setProductCur({});
    }
  };

  const handleAddPro = (product, skuInfo = null) => {
    if (!utils.getToken()) {
      Taro.navigateTo({
        url: '/pages/other/login/index',
      });
      return;
    }
    dispatch({
      type: 'takeOut/addProductToCarModel',
      payload: {
        merchantId: params.merchantId,
        orgId: params.orgId,
        orgName: params.orgName,
        productReleaseId: product.id,
        productVariantReleaseId: skuInfo ? skuInfo.id : product.variantId,
        type: 4,
        favouredId: skuInfo ? skuInfo.activityId : product.activityId,
        favouredType: skuInfo ? skuInfo.type : product.activityType,
      },
    }).then((rst) => {
      if (rst == 'success') {
        getCarProList();
      }
    });
  };

  const handlePurchaseNum = debounce(async (type, product) => {
    let { num, id, activityLimit } = product;
    if (type === 'add') {
      num++;
      if (activityLimit > 0 && num == parseInt(activityLimit) + 1) {
        Taro.showToast({
          title: '该折扣商品限购' + activityLimit + '份,超过' + activityLimit + '份恢复原价',
          icon: 'none',
          mask: false,
          duration: 2000,
        });
      }
    }
    if (type === 'sub') num--;
    if (type === 'sub' && num < 1) {
      await dispatch({
        type: 'productCar/deleteDeleteProduct',
        payload: { id },
      });
    } else {
      await dispatch({
        type: 'productCar/updateProductNum',
        payload: { id, num },
      });
    }
    getCarProList();
  }, 800);

  const handleCartPay = () => {
    handleClose();
    handleGoPay();
  };

  const goPriceExplain = () => {
    Taro.navigateTo({
      url: '/mainSubPack/priceExplain/index',
    });
  };

  let totalSelProNum = 0;
  if (carProList.length > 0) {
    carProList.map((item) => {
      totalSelProNum += parseInt(item.num);
    });
  }

  return (
    <View className="takeOutGoodsDetail">
      <SkuSelect
        isOpened={isOpenedSku}
        product={productCur}
        handleAddPro={handleAddPro}
        handlePurchaseNum={handlePurchaseNum}
        handleClose={handleClose}
        dispatch={dispatch}
      />

      <ShoppingCarList
        isOpened={isOpenedCar}
        totalSelProNum={totalSelProNum}
        totalSelProMoney={totalMoney.totalPayment}
        totalPrice={totalMoney.totalPrice}
        minMoney={params.minMoney}
        deliveryMoney={params.deliveryMoney}
        delivery={delivery}
        carProList={carProList}
        handlePurchaseNum={handlePurchaseNum}
        handleClose={handleClose}
        handlePay={handleCartPay}
      />

      <DistributionWayLayout
        {...{
          isOpened: !!distributionWayGroup,
          onClose: () => {
            setDistributionWayGroup();
          },
          value: distributionWayGroup,
          onChange: (theProductList) => {
            goToBuy(theProductList);
          },
        }}
      />

      <Image
        className="goodImg"
        src={
          productDetail.url?.indexOf('http') === 0
            ? productDetail.url
            : sourceUrl + productDetail.url
        }
      />

      <View className="detailLine">
        <View className="name">{productDetail.title || ''}</View>
        <View className="saleNum txt20 gray">月售{productDetail.monthlySale || '0'}份</View>
        <View className="detailBottom flex-row-spaceBetween">
          <View className="priceAct flex-column">
            <View className="price">
              <Text className="zUnit customePageStyle">¥</Text>
              <Text className="zNum customePageStyle">{parseInt(productDetail.price)}</Text>
              <Text className="zNumMore customePageStyle">
                {utils.getDotStr(productDetail.price)}
              </Text>
              {productDetail.activityType == 3 && (
                <Text className="zOldNum txt22 gray">¥{productDetail.cost}</Text>
              )}
            </View>
            {productDetail.activityType == 3 && (
              <View className="activityInfo flex-row-center-center customePageBorderStyle50 customePageStyle">
                <Icon name="icon_labe" size={18} color={customeColor} />
                <Text className="discount">{productDetail.discount}折</Text>
                <Text className="diliver customePageBackgroundStyle"></Text>
                <Text className="activityLimit">
                  {productDetail.activityLimit == 0
                    ? '不限购'
                    : '限' + productDetail.activityLimit + '份'}
                </Text>
              </View>
            )}
          </View>
          <View className="ops flex-column-end-end">
            {checkProductIsSoldOut(productDetail, 'totalInventoryQuantity') === 0 ? (
              <View className="sold-out flex-row-center-center">
                <View className="sold-out-txt">已售罄</View>
              </View>
            ) : productDetail.isMutilSku ? (
              <View
                className="skuSel customePageBackgroundStyle flex-row-center-center"
                onClick={() => handleSku(productDetail)}
              >
                选择规格
                {productDetail.carNum > 0 && (
                  <Text className="num flex-row-center-center">{productDetail.carNum}</Text>
                )}
              </View>
            ) : productDetail.carNum > 0 ? (
              <View className="opCart flex-row--center">
                {/* todo：更新图库并换减号图标 */}
                <Icon
                  name="a-icon_minus_huaban7fuben8"
                  size={40}
                  color={customeColor}
                  onClick={() => handlePurchaseNum('sub', productDetail.carList[0])}
                />
                <Text className="num">{productDetail.carNum}</Text>
                <Icon
                  name="icon_add"
                  size={40}
                  color={customeColor}
                  onClick={() => handlePurchaseNum('add', productDetail.carList[0])}
                />
              </View>
            ) : (
              <View
                className="btnCart flex-row-center-center customePageBackgroundStyle"
                onClick={() => handleAddPro(productDetail, null)}
              >
                加入购物车
              </View>
            )}
          </View>
        </View>
      </View>

      <View className="detailInfo">
        <View className="lable">商品简介</View>
        <View className="detailArea">
          <View
            className="detail"
            dangerouslySetInnerHTML={{
              __html: productDetail.bodyHtml,
            }}
          ></View>
        </View>
        <View className="priceAdjust flex-row--center" onClick={goPriceExplain}>
          <Text className="txt24 gray">价格说明</Text>
          <Image className="priceImg" src={questionImg} />
        </View>
      </View>

      <View className="takeOutDetailBottom flex-column">
        {productDetail?.reductionString?.length > 0 && (
          <View className="manjianInfo flex-row-center-center">
            {productDetail.reductionString}
          </View>
        )}
        <View className="bottomCtx flex-row--center">
          <View className="tab flex-column--center" onClick={handleCar}>
            <Image className="icon" src={cartImg} />
            <View className="name">购物车</View>
            {totalSelProNum > 0 && (
              <View
                className={[
                  'gwcNum',
                  totalSelProNum > 9 && 'two',
                  totalSelProNum > 99 && 'three',
                ].join(' ')}
              >
                {totalSelProNum > 99 ? '99+' : totalSelProNum}
              </View>
            )}
          </View>

          <View className="feeArea flex-column-end">
            <View className="totalLine">
              <Text className="txt20">合计：</Text>
              <Text className="txt24 customePageStyle bold">¥</Text>
              <Text className="txt32 customePageStyle bold total">
                {totalMoney.totalPayment.toFixed(2)}
              </Text>
              {totalMoney.totalPrice > totalMoney.totalPayment && (
                <Text className="txt22 gray cheaper">{totalMoney.totalPrice.toFixed(2)}</Text>
              )}
            </View>
            <View className="sendLine txt20 black6">
              {delivery != null && delivery.isInDelivery > 0
                ? delivery.isInDelivery == 2
                  ? '超出配送范围'
                  : delivery.fee > 0
                  ? '另需配送费¥' + delivery.fee
                  : '免配送费'
                : ''}
            </View>
          </View>

          {totalSelProNum > 0 && totalMoney.totalPayment >= params.minMoney ? (
            <View
              className="btnPay flex-row-center-center customePageBackgroundStyle"
              onClick={handleGoPay}
            >
              去结算
            </View>
          ) : (
            <View className="btnPay unableBtn flex-row-center-center">¥{params.minMoney}起送</View>
          )}
        </View>
        {Taro.$bottomHight && <View className="bottomHt"></View>}
      </View>
    </View>
  );
};

export default connect(({ takeOut, productCar }) => ({
  productDetail: takeOut.takeOutProductDetail,
  selectedAddress: productCar.selectedAddressTakeOut,
}))(TakeOutGoodsDetail);
